<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class App_sample extends MY_Controller {
	
	// Define Allowed Extension for File Upload
	var $arr_allowed_upload	= array('txt','jpg', 'jpeg', 'png', 'bmp', 'gif','ppt','pptx','xls','xlsx','doc','docx','pdf');
	
	function __construct()
	{
		parent::__construct(); 
		
		// Uses Model
		$this->load->model('sample_master_model', 'Master');
		$this->load->model('sample_reference_model', 'Ref');
		$this->load->model('sample_detail1_model', 'Detail1');
		$this->load->model('sample_detail2_model', 'Detail2');
		$this->load->model('sample_detail_file_model', 'DetailFile');
		$this->load->model('combo_model', 'Combo');
		
		// Secure Page With Session
		$this->secure_session();
	}
	
	function index(){
		// Display Index
		$data['title'] = $this->session_menu_label;
		
		viewByTemplate('app_sample/index', $data, 'grid');
	}
	
	function getdata()
	{
		// Ajax Response For Datagrid
		echo $this->Master->GetJSON();
	}
	
	function getimportdata()
	{
		// Ajax Response For Datagrid
		echo $this->Master->GetImportJSON();
	}
	
	function dtl_sample1_data()
	{
		// Ajax Response For Datagrid
		echo $this->Detail1->GetJSON(post('pk_master'));
	}
	
	function dtl_sample2_data()
	{
		// Ajax Response For Datagrid
		echo $this->Detail2->GetJSON(post('pk_master'));
	}
	
	function dtl_sample_file_data()
	{
		// Ajax Response For Datagrid
		echo $this->DetailFile->GetJSON(post('pk_master'));
	}
	
	function create()
	{
		// Display Form Create
		$data['title'] = "Tambah Data Master";
		$data['data'] = NULL;
		
		// Define Combo Data
		$data['arr_reference']	= $this->Combo->SampleReference();
		$data['arr_province']	= $this->Combo->SWProvince();
		
		$data['mode'] = "create";
		viewByTemplate('app_sample/form', $data, 'form');
	}

	function edit()
	{
		// Display Form Edit
		$data['title'] = "Ubah Data Master";
		$data['data'] = $this->Master->GetSingleView(get('pk_master'));
		
		// Define Combo Data
		$data['arr_reference']	= $this->Combo->SampleReference();
		$data['arr_province']	= $this->Combo->SWProvince();
		
		$data['file_allowed']		= implode(', ', $this->arr_allowed_upload);
		
		$data['mode'] = "edit";
		viewByTemplate('app_sample/form', $data, 'form');
	}
	
	function view()
	{
		// Display Form View
		$data['title'] = "View Data Master";
		$data['data'] = $this->Master->GetSingleView(get('pk_master'));
		
		// Define Combo Data
		$data['arr_reference']	= $this->Combo->SampleReference();
		$data['arr_province']	= $this->Combo->SWProvince();
		
		$data['file_allowed']		= implode(', ', $this->arr_allowed_upload);
		
		$data['mode'] = "view";
		viewByTemplate('app_sample/form', $data, 'form');
	}
	
	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");


		// Validation
		if (post("pk_master") == '') {
			$error->Add("pk_master", "Primary Key", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT COUNT(1) FROM sample_master WHERE UPPER(pk_master) = '".@strtoupper(@trim(post("pk_master")))."'")) > 0) {
			$error->Add("pk_master", "Primary Key", $tpl_duplicate);
		}
		
		return $error;
	}
	
	function ajax_post()
	{
		// Ajax Response For Submit Form
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";
		
		// Get Error Template
		$tpl_insert_success = $this->MessageTemplate("CS001");
		$tpl_update_success = $this->MessageTemplate("CS002");
		
		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{
				// Fill Post Data Array
				$data	= post_by_key(array('pk_master','field1','field2','field3','field4','field5','field6','field7',
											'ref_key_combo','ref_key_lov','province_code','city_code'));
				
				// Set Primary Key Variable
				$data['pk_master']	= @strtoupper(@trim(post("pk_master")));
				$pk_master	= $data['pk_master'];
				
				// Set Date Format
				$data['field2']	= ($data['field2'] == '' ? NULL : date_format3($data['field2'], 'YYYY-MM-DD'));
				$data['field3']	= ($data['field3'] == '' ? NULL : date_format3($data['field3'], 'YYYY-MM-DD'));
				
				// Set Number Format
				$data['field4']	= (float)toNumber($data['field4']);
				$data['field5']	= (float)toNumber($data['field5']);
				
				if (post("mode") == "create")
				{
					$ls_genid	= $pk_master;
					
					$data['create_date']	= NOW;
					$data['create_id']		= USERID;
					
					$this->Master->Add($data);
					
					$ls_response = $tpl_insert_success['message_id'];
				}
				else if (post("mode") == "edit")
				{
					unset($data['pk_master']);
					
					$data['modify_date']	= NOW;
					$data['modify_id']		= USERID;
					
					$this->Master->Update(	$data, 
											array('pk_master'	=> $pk_master));
					
					$ls_response = $tpl_update_success['message_id'];
				}
				
				
				// ----- >> Detail Sample 1
				$dtl_sample1	= $this->data['dtl_sample1'];
				$total_deleted	= $dtl_sample1['num_row']['deleted'];
				$total_inserted	= $dtl_sample1['num_row']['inserted'];
				$total_updated	= $dtl_sample1['num_row']['updated'];
				for($i=0,$max_i=$total_deleted; $i<$max_i; $i++){
					$row = $dtl_sample1['deleted'][$i];
					
					$this->Detail1->DeleteSingle($row['pk_master'], $row['index_no']);
				}
				for($i=0,$max_i=$total_inserted; $i<$max_i; $i++){
					$row = $dtl_sample1['inserted'][$i];
					
					$row['index_no']	= $this->get_data("SELECT NVL((SELECT MAX(index_no) FROM sample_detail1 WHERE pk_master = '".$pk_master."'),0)+1 seqid FROM DUAL");
					if($row['tgl_field']==''){ unset($row['tgl_field']); }else{ $row['tgl_field']=date_format3($row['tgl_field'],'YYYY-MM-DD'); }
					
					$row['pk_master'] = $pk_master;
					$row['create_date']	= NOW;
					$row['create_id']	= USERID;
					
					$this->Detail1->Add($row);
				}
				for($i=0,$max_i=$total_updated; $i<$max_i; $i++){
					$row = $dtl_sample1['updated'][$i];
					
					$index_no	= $row['index_no'];
					unset($row['index_no']);
					
					if($row['tgl_field']==''){ unset($row['tgl_field']); }else{ $row['tgl_field']=date_format3($row['tgl_field'],'YYYY-MM-DD'); }
					
					$row['modify_date']	= NOW;
					$row['modify_id']	= USERID;
				
					$this->Detail1->Update($row, array(	'pk_master'	=> $pk_master, 
														'index_no'	=> $index_no));
				}
				
				
				
				// ----- >> Detail Sample 2
				$dtl_sample2	= $this->data['dtl_sample2'];
				$total_deleted	= $dtl_sample2['num_row']['deleted'];
				$total_inserted	= $dtl_sample2['num_row']['inserted'];
				$total_updated	= $dtl_sample2['num_row']['updated'];
				for($i=0,$max_i=$total_deleted; $i<$max_i; $i++){
					$row = $dtl_sample2['deleted'][$i];
					
					$this->Detail2->DeleteSingle($row['pk_master'], $row['index_no']);
				}
				for($i=0,$max_i=$total_inserted; $i<$max_i; $i++){
					$row = $dtl_sample2['inserted'][$i];
					
					$row['index_no']	= $this->get_data("SELECT NVL((SELECT MAX(index_no) FROM sample_detail2 WHERE pk_master = '".$pk_master."'),0)+1 seqid FROM DUAL");
					$row['jumlah']		= (float)$row['jumlah'];
					
					$row['pk_master'] = $pk_master;
					$row['create_date']	= NOW;
					$row['create_id']	= USERID;
					
					$this->Detail2->Add($row);
				}
				for($i=0,$max_i=$total_updated; $i<$max_i; $i++){
					$row = $dtl_sample2['updated'][$i];
					
					$index_no	= $row['index_no'];
					unset($row['index_no']);
					
					$row['jumlah']		= (float)$row['jumlah'];
					
					$row['modify_date']	= NOW;
					$row['modify_id']	= USERID;
				
					$this->Detail2->Update($row, array(	'pk_master'	=> $pk_master, 
														'index_no'	=> $index_no));
				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}
	
	function submit_upload_file(){
		$ls_genid		= '';
		$ls_response	= '';
		$num_file		= 4;
		$arr_allowed	= $this->arr_allowed_upload;
		$config['upload_path']		= APPPATH . '/../files/';
		$config['allowed_types']	= $arr_allowed;
		$this->load->library('upload', $config);
		
		$error = new ErrorList();
		
		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");
		$tpl_typefile	= $this->MessageTemplate("ER011");
		$tpl_filesize	= $this->MessageTemplate("ER013");
		$tpl_upload_success = $this->MessageTemplate("CS004");
		
		// Get Server Maximum Upload File Size 
		// (publisher : http://www.kavoir.com/2010/02/php-get-the-file-uploading-limit-max-file-size-allowed-to-upload.html)
		$max_upload		= (int)(@ini_get('upload_max_filesize'));
		$max_post		= (int)(@ini_get('post_max_size'));
		$memory_limit	= (int)(@ini_get('memory_limit'));
		$max_upload_mb	= @min($max_upload, $max_post, $memory_limit);
		$content_length	= (array_key_exists('CONTENT_LENGTH',$_SERVER) ? $_SERVER['CONTENT_LENGTH'] : 0);
		
		// Validation
		$has_file	= false; $arr_uploaded	= array();
		if($content_length/1048576 > $max_upload_mb){
			$error->Add("my_file1", 
						array(stringFileSize($content_length), $max_upload_mb.'MB'), 
						$tpl_filesize);
		}else{
			for($i=1, $max_i=$num_file; $i<=$max_i; $i++){
				$filename	= $_FILES['my_file'.$i]['name'];
				$ext		= strtolower(end(explode('.', $filename)));
				$arr_uploaded[$i]	= '';
				
				if(trim($filename) != ''){
					$has_file = true;
					$new_filename	= 'UPL.'.str_pad(get('pk_master'),5,'0',STR_PAD_LEFT).'.'.md5(USERID.NOW.$i);
					
					if(!in_array($ext, $arr_allowed)){
						$error->Add("my_file".$i, 
									array($_FILES['my_file'.$i]['type'], json_encode($arr_allowed)), 
									$tpl_typefile);
					}else if ( !$this->upload->do_upload('my_file'.$i, $new_filename) )
					{
						$error->addMessage($this->upload->display_errors('', ''));
					} else {
						$arr_uploaded[$i] = $new_filename;
					}
				}
			}
			if(!$has_file){ $error->Add("my_file1", "File", $tpl_empty); }
		}
		
		
		try
		{
			$err_msg = $error->getMessage();
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else if (trim($err_msg) != '') { $is_error = 1; $ls_response = $error->getMessage(); }
			else
			{
				for($i=1, $max_i=$num_file; $i<=$max_i; $i++){
					$filename	= $_FILES['my_file'.$i]['name'];
					$ext		= strtolower(end(explode('.', $filename)));
					
					if(trim($filename) != '' && in_array($ext, $arr_allowed) && $arr_uploaded[$i]!=''){
						$new_filename	= $arr_uploaded[$i].'.'.$ext;
						
						$row	= array('pk_master'	=> get('pk_master'),
										'filename'	=> $new_filename,
										'ext'		=> $ext,
										'mime_type'	=> $_FILES['my_file'.$i]['type'],
										'label'		=> $filename,
										'filesize'	=> $_FILES['my_file'.$i]['size'],
										'create_id'	=> USERID,
										'create_ipaddress'	=> client_ip(),
										'create_date'=> NOW );
						$this->DetailFile->Add($row);
						
						unset($row);
					}
				}
				
				$ls_response = $tpl_upload_success['message_id'];
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}
	
	function ajax_delete()
	{
		$ls_result	= "";
		$pk_master	= get('pk_master');
		
		if ($pk_master != "")
		{
			// Delete Single
			$arr_rule	= array('pk_master' => $pk_master);
			$ls_result = $this->Master->DeleteSingle($arr_rule);
		}
		else
		{
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				
				$arr_rule	= array('pk_master' => $row['pk_master']);
				$ls_result .= $this->Master->DeleteSingle($arr_rule);
			}
		}
		
		echo $ls_result;
	}
	
	function ajax_delete_file()
	{
		$ls_result	= "";
		$pk_master	= get('pk_master');
		$filename	= get('filename');
		
		if ($pk_master != "")
		{
			// Delete Single
			@unlink(APPPATH . '/../files/' . $filename);
			$arr_rule	= array('pk_master' => $pk_master,
								'filename'	=> $filename);
			$ls_result	= $this->DetailFile->DeleteSingle($arr_rule);
		}
		else
		{
			
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				@unlink(APPPATH . '/../files/' . $row['filename']);
				$arr_rule	= array('pk_master' => $row['pk_master'],
									'filename'	=> $row['filename']);
				$ls_result .= $this->DetailFile->DeleteSingle($arr_rule);
			}
		}
		
		echo $ls_result;
	}
	
	function download_sample_file(){
		$this -> secure_session();
		/* copyleft : http://elouai.com/force-download.php */
		
		$filename 			= APPPATH . '/../files/' . get('filename');
		$download_file_name	= $this->get_data("SELECT label FROM sample_detail_file WHERE filename = '" . get('filename') . "'");
		$download_file_name	= str_replace(':','.', str_replace(' ','_', str_replace('_NOW_', NOW, $download_file_name)));
		
		// required for IE, otherwise Content-disposition is ignored
		if(ini_get('zlib.output_compression'))
			ini_set('zlib.output_compression', 'Off');
		
		// addition by Jorg Weske
		$file_extension = strtolower(substr(strrchr($filename,"."),1));
		
		if($filename == "") 
		{
			echo "<script type=\"text/javascript\">alert('ERROR: download file NOT SPECIFIED.');</script>";
			exit;
		} elseif ( ! file_exists( $filename ) ) 
		{
			echo "<script type=\"text/javascript\">alert('ERROR: File $filename not found.');</script>";
			exit;
		};
		
		switch( $file_extension )
		{
			case "pdf": $ctype="application/pdf"; break;
			case "exe": $ctype="application/octet-stream"; break;
			case "zip": $ctype="application/zip"; break;
			case "doc": $ctype="application/msword"; break;
			case "xls": $ctype="application/vnd.ms-excel"; break;
			case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
			case "gif": $ctype="image/gif"; break;
			case "png": $ctype="image/png"; break;
			case "jpeg":
			case "jpg": $ctype="image/jpg"; break;
			default: $ctype="application/force-download";
		}
		header("Pragma: public"); // required
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false); // required for certain browsers 
		header("Content-Type: $ctype");
		// change, added quotes to allow spaces in filenames, by Rajkumar Singh
		//header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
		header("Content-Disposition: attachment; filename=\"".$download_file_name."\";" );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($filename));
		readfile("$filename");
		exit();
	}
	
	
	
	/* ----- >> Example For Print Using FPDF
	 Publisher	: www.fpdf.org
	 Usage		: just copy all function, set variable for data, set view for layout
	 Log		:	Date			PIC			Desc
					18/02/2013		Pitra		Add New Example
	*/
	function cetak(){
		$as_pk_master	= get('pk_master');
		
		if($as_pk_master!='' && $as_pk_master!=''){
			
			// Load FPDF
			$this->load->helper('fpdf');
			
			// Set Data
			$data['data']			= $this->Master->GetSingleView($as_pk_master);
			$data['arr_detail1']	= $this->Detail1->GetDetailByID($as_pk_master);
			$data['arr_detail2']	= $this->Detail2->GetDetailByID($as_pk_master);
			
			// Load View
			$this->load->view('app_sample/cetak', $data);
			
		}
	}
	
	
	
	/* ----- >> Example For Download Data
	 Publisher	: phpexcel.codeplex.com
	 Usage		: just copy all function and modify $ls_sql and title for cell A1 
	 Log		:	Date			PIC			Desc
					18/02/2013		Pitra		Add New Example
	*/
	function download(){
		$filename			= APPPATH . '/file/cache/' . _SESSID.'.xls';
		@unlink($filename);
		$this->load->helper('file');
		
		$arr_alphabet	= array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EL', 'EK', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ');
		
		$ls_sql	= "	SELECT	*
					FROM 	sample_master
					ORDER BY pk_master ASC";
						
						
		$result			= $this -> db -> query($ls_sql);
		$arr_data		= $result->result_array();
		
		if(count($arr_data)==0){ echo 'Data Empty..'; die; }
		
		require_once APPPATH . "third_party/PHPExcel.php";
		require_once APPPATH . "third_party/PHPExcel/IOFactory.php";
		
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();

		// Set properties
		$objPHPExcel->getProperties()->setCreator("Plitasoft")
									 ->setLastModifiedBy("Plitasoft")
									 ->setTitle("Office 2007 XLSX Import Data Document")
									 ->setSubject("Office 2007 XLSX Import Data Document")
									 ->setDescription("Import data document for Office 2007 XLSX, generated using PHP classes.")
									 ->setKeywords("office 2007 openxml php")
									 ->setCategory("Import result file");
		
		@set_time_limit(0);                   // ignore php timeout
		//@ignore_user_abort(true);             // keep on going even if user pulls the plug*
		
		$styleH1 = array('font' => array('bold' => true, 'size' => 18));
		$styleH2 = array('font' => array('bold' => true));
		
		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'LIST DATA');
		$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleH1);
		
		$ln_index	= 2;
		for($i=0,$max_i=count($arr_data); $i<$max_i; $i++){
			$row	= $arr_data[$i];
			if($i==0){ $arr_key	= array_keys($row); }
				
			// Add some data, we will use printing features
			// Header
			if($i==0){
				for($j=0, $max_j=count($arr_key); $j<$max_j; $j++){
					$field_name	= $arr_key[$j];
					
					$ls_coordinate	= $arr_alphabet[$j] . ($ln_index);
					$objPHPExcel->getActiveSheet()->setCellValue($ls_coordinate, $field_name);
					$objPHPExcel->getActiveSheet()->getStyle($ls_coordinate)->applyFromArray($styleH2);
				}
				$ln_index++;
			}
			
			// Data
			for($j=0, $max_j=count($arr_key); $j<$max_j; $j++){
				$field_name	= $arr_key[$j];
				$value		= $row[$field_name];
				
				$value	= str_replace("\t", '\t', $value);
				$value	= str_replace("\n",'\n', $value);
				$value	= str_replace(chr(10),'\n', $value);
				$value	= str_replace(chr(13),'\n', $value);
				if($j==4){ $value = strip_tags($value); }
				
				$ls_coordinate	= $arr_alphabet[$j] . ($ln_index);
				//echo $ls_coordinate.' ; ';
				$objPHPExcel->getActiveSheet()->setCellValue($ls_coordinate, $value);
			}
			$ln_index++;
		}
		
		
		// ------ >> Save EXCEL
		if(count($arr_data)>0){
			// Rename sheet
			//echo date('H:i:s') . " Rename sheet\n";
			$objPHPExcel->getActiveSheet()->setTitle('Sheet 1');
			
			// Set active sheet index to the first sheet, so Excel opens this as the first sheet
			$objPHPExcel->setActiveSheetIndex(0);

			// Save Excel 2007 file
			//echo date('H:i:s') . " Write to Excel2007 format\n";
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$objWriter->save($filename);

		}
	}
	
	function ajax_store_procedure(){
		$pk_master		= get('pk_master');
		$as_newvalue	= get('as_newvalue');
		
		// Store Procedure Without Return
		$this->db->query("EXEC SP_TEST_WITHOUT_RETURN '".$pk_master."', '".$as_newvalue."'");
		
		
		// Store Procedure With Return
		$result= $this->db->query("EXEC SP_TEST_WITH_RETURN '".$pk_master."'");
		$arr_data	= $result->result_array();
		if(count($arr_data) > 0){
			echo $arr_data[0]['field1'];
		}else{
			echo 'No Return';
		}
	}
	
	
	/* ----- >> Example For Import Data
	 Log		:	Date			PIC			Desc
					12/11/2013		Pitra		Add New Example
	*/
	function form_import(){
		$data['title'] = "Import Data From Excel";
		
		$this->load->view('app_sample/form_import', $data);
		//viewByTemplate('app_sample/form_import', $data, 'form');
	}
	
	function process_upload_file(){
		$is_error		= 0;
		$arr_allowed	= array('xls');
		$config['upload_path']		= APPPATH . '/file/upload/';
		$config['allowed_types']	= $arr_allowed;
		$this->load->library('upload', $config);
		
		$error = new ErrorList();
		
		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");
		$tpl_typefile	= $this->MessageTemplate("ER011");
		$tpl_filesize	= $this->MessageTemplate("ER013");
		$tpl_upload_success = $this->MessageTemplate("CS004");
		
		// Get Server Maximum Upload File Size 
		// (publisher : http://www.kavoir.com/2010/02/php-get-the-file-uploading-limit-max-file-size-allowed-to-upload.html)
		$max_upload		= (int)(@ini_get('upload_max_filesize'));
		$max_post		= (int)(@ini_get('post_max_size'));
		$memory_limit	= (int)(@ini_get('memory_limit'));
		$max_upload_mb	= @min($max_upload, $max_post, $memory_limit);
		$content_length	= (array_key_exists('CONTENT_LENGTH',$_SERVER) ? $_SERVER['CONTENT_LENGTH'] : 0);
		
		// Validation
		$has_file	= false; $arr_uploaded	= array();
		if($content_length/1048576 > $max_upload_mb){
			$ls_response	= $tpl_filesize['message_id'];
			$ls_response	= str_replace('{0}', stringFileSize($content_length), $ls_response);
			$ls_response	= str_replace('{1}', $max_upload_mb.'MB', $ls_response);
			
			$is_error = 1;
		}else{
			$filename	= $_FILES['my_file']['name'];
			$ext		= strtolower(end(explode('.', $filename)));
			
			if(trim($filename) != ''){
				$new_filename	= md5(USERID);
				
				@unlink($config['upload_path'].$new_filename.'.'.$ext);
				
				if(!in_array($ext, $arr_allowed)){
					$ls_response	= $tpl_typefile['message_id'];
					$ls_response	= str_replace('{0}', '["'.$ext.'"]', $ls_response);
					$ls_response	= str_replace('{1}', json_encode($arr_allowed), $ls_response);
					
					$is_error = 1;
				}else if ( !$this->upload->do_upload('my_file'.$i, $new_filename) )
				{
					$ls_response = $this->upload->display_errors('', '');
					
					if(trim($ls_response) == ''){ $is_error = 1; }
				}
			}else{
				$ls_response	= $tpl_empty['message_id'];
				$ls_response	= str_replace('{0}', 'File', $ls_response);

				$is_error = 1;
			}
		}
		
		if($is_error == 1){
			echo '<script type="text/javascript">parent.setLoading(false); parent.$.messager.alert("Error","'.addslashes($ls_response).'","error");</script>';
		}else{
			echo '<script type="text/javascript">parent.f_import_file_to_db("'.$new_filename.'.'.$ext.'");</script>';
		}
	}
	
	function import_file_to_db(){
		$filename 		= post('filename');
		$path 			= APPPATH . '/file/upload/' . $filename;
		
		@set_time_limit(0);				// ignore php timeout
		//@ignore_user_abort(true);		// keep on going even if user pulls the plug*
		
		$this->load->helper('excel_reader');
		error_reporting(E_ALL ^ E_NOTICE);
		$data = new Spreadsheet_Excel_Reader($path);
		$sheet = 0;
		
		$arr_fieldname	= array('FIELD1', 'FIELD2', 'FIELD3', 'FIELD4', 'FIELD5');
		$num_rows	= $data->rowcount($sheet);
		
		$count_success	= 0;
		$count_error	= 0;
		$error_logfile	= APPPATH . '/file/cache/' . _SESSID .'.error_log.txt';
		@unlink($error_logfile);
		
		// Delete Temporary Data
		$this->db->delete('SAMPLE_IMPORT', array('SESSID' => _SESSID));
		
		for($i = 2, $max_i = $num_rows; $i<=$max_i; $i++){
			$row = array();
			$row['rows']	= $i;
			for($col=1;$col<=$data->colcount($sheet);$col++) {
				$val		= trim($data->val($i,$col,$sheet));
				$key		= $arr_fieldname[$col-1];
				
				$row[$key]	= $val;
			}
			
			// -- >> Process
			if(count(array_keys($row))>=count($arr_fieldname)){
				$lb_valid = true;
				$ls_error = '';
				
				if($row['FIELD1'] == ''){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD1 is empty';
					$lb_valid	= false;
				}
				
				if($row['FIELD2'] == ''){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD2 is empty';
					$lb_valid	= false;
				}else if(!is_date($row['FIELD2'])){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD2 is not date';
					$lb_valid	= false;
				}
				
				if($row['FIELD3'] == ''){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD3 is empty';
					$lb_valid	= false;
				}else if(!is_date($row['FIELD3'])){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD3 is not date';
					$lb_valid	= false;
				}
				
				if($row['FIELD4'] == ''){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD4 is empty';
					$lb_valid	= false;
				}else if(!is_numeric($row['FIELD4'])){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD4 is not numeric';
					$lb_valid	= false;
				}
				
				if($row['FIELD5'] == ''){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD5 is empty';
					$lb_valid	= false;
				}else if(!is_numeric($row['FIELD5'])){
					$ls_error	.= ($ls_error==''?'':',') . 'FIELD5 is not numeric';
					$lb_valid	= false;
				}
				
				
				if($lb_valid){
					unset($row['rows']);
					$row['SESSID']		= _SESSID;
					$row['INDEX_NO']	= $i-1;
					$row['FIELD2']		= date_format3($row['FIELD2'],'YYYY-MM-DD');
					$row['FIELD3']		= date_format3($row['FIELD3'],'YYYY-MM-DD');
					$row['FIELD4']		= (float)$row['FIELD4'];
					$row['FIELD5']		= (float)$row['FIELD5'];
					$row['CREATE_DATE']	= NOW;
					$row['CREATE_ID']	= USERID;
					
					// Insert Temporary Data
					$this->db->insert('SAMPLE_IMPORT', $row);
					$count_success++;
				}else{
					$ls_error = 'Line '.str_pad($i, 5, '0', STR_PAD_LEFT).' >> '.$ls_error;
					$count_error++;
					
					write_file($error_logfile, $ls_error."\n", 'a+');
				}
			}
			
		}
		
		$ls_response = "Import Process ".$num_rows." row(s) data Finished<br />- ".$count_success." success<br />- ".$count_error." failed  (".($count_error==0?'':"<a href=\"#\" onclick=\"document.getElementById('if_download').src=gs_path+'/app/download/?file=".end(explode('/',$error_logfile))."&filename=errorlog.txt';\">download log</a>)");
		echo 'setLoading(false); grid_import_reload(); $.messager.alert("Notification","'.addslashes($ls_response).'","ok");';
		
		if($count_success > 0){
			echo "$('#label_file_import, #my_file, #btn_upload').hide(); $('#btn_import, #btn_new_import').fadeIn();";
		}else{
			echo "f_new_import();";
		}
	}
	
	function import_transfer(){
		// ------------------------------
		// Process your data here
		// ------------------------------
		try {
			$this->db->query("BEGIN SP_SAMPLE_IMPORT('"._SESSID."','".USERID."'); END;");
		} catch(Exception $e) {
			return $e->getMessage();
		}
		
		// Delete Temporary Data
		$this->db->delete('SAMPLE_IMPORT', array('SESSID' => _SESSID));
		
		echo 'setLoading(false); grid_import_reload(); grid_reload(); f_new_import(); $.messager.alert("Success","Proses import selesai","ok"); ';
	}
}
?>